package lc20240509;

import java.util.Stack;

public class Demo1 {
    public static void main(String[] args) {
        String[] tokens={"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
         System.out.println(evalRPN(tokens));

    }
    //自己的写法
    public static int evalRPN(String[] tokens) {
        int len=tokens.length;
        if (len==1){
            return Integer.parseInt(tokens[0]);
        }
        int sum=0;
        Stack<Integer> stack=new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            char c=tokens[i].charAt(0);
            try {
                int num=Integer.parseInt(tokens[i]);
                stack.push(num);
            }catch (NumberFormatException e){
                int a=stack.pop();
                int b=stack.pop();
                if (c=='+'){
                    sum=stack.push((b+a));
                }
                else if (c=='-'){
                    sum=stack.push((b-a));
                }
                else if (c=='*'){
                    sum=stack.push((b*a));
                }
                else if (c=='/'){
                    sum=stack.push((b/a));
                }
            }
        }
        return sum;
    }

    //gpt解法
    public static int evalRPN1(String[] tokens){
        Stack<Integer> stack = new Stack<>();
        // 遍历tokens数组
        for (String token : tokens) {
            // 根据token的内容进行操作
            switch (token) {
                case "+":
                    stack.push(stack.pop() + stack.pop());
                    break;
                case "-":
                    // 注意减法和除法的操作顺序
                    int operand2 = stack.pop();
                    int operand1 = stack.pop();
                    stack.push(operand1 - operand2);
                    break;
                case "*":
                    stack.push(stack.pop() * stack.pop());
                    break;
                case "/":
                    operand2 = stack.pop();
                    operand1 = stack.pop();
                    stack.push(operand1 / operand2);
                    break;
                default:
                    // 如果是数字，则直接入栈
                    stack.push(Integer.parseInt(token));
                    break;
            }
        }
        // 最终栈顶的元素即为表达式的结果
        return stack.pop();
    }
}
